package _05_二叉树;

import java.util.*;

/**
 * https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
 */
public class _144_二叉树的前序遍历 {

    // 递归
    public List<Integer> preorderTraversal1(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        preorderTraversal(root, list);
        return list;
    }

    public void preorderTraversal(TreeNode root, List<Integer> list) {
        while (root != null) {
            if (root.left != null) {
                TreeNode pred = root.left;
                while (pred.right != null && pred.right != root) {
                    pred = pred.right;
                }
                if (pred.right == null) {
                    list.add(root.val);
                    pred.right = root;
                    root = root.left;
                } else {
                    pred.right = null;
                    root = root.right;
                }
            } else {
                list.add(root.val);
                root = root.right;
            }
        }
    }

    public void preorderTraversal1(TreeNode root, List<Integer> list) {
        if (root == null) return;

        list.add(root.val);

        preorderTraversal(root.left, list);

        preorderTraversal(root.right, list);
    }

    // 迭代, 模拟栈操作
    public List<Integer> preorderTraversal2(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();

        // 从根节点出发，查询到最左边节点
        while (true) {
            list.add(root.val);
            if (root.right != null) stack.push(root.right);

            if (root.left == null) {
                // 遍历右边节点, 当前节点和根节点操作一样，所以赋值给root
                if (stack.isEmpty()) {
                    break;
                } else {
                    root = stack.pop();
                }
            } else {
                root = root.left;
            }
        }
        return list;

    }


    // 迭代，方法2 根，左，右
    public List<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();

            list.add(node.val);

            if (node.right != null) stack.push(node.right);

            if (node.left != null) stack.push(node.left);

        }

       return list;
    }
}
